package cn.support.neo.mvp.core.provider;

import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.widget.Toast;

import cn.support.neo.mvp.R;
import cn.support.neo.mvp.core.base.ResultException;
import cn.support.neo.mvp.core.event.UserInfoChangeEvent;
import cn.support.neo.mvp.model.entity.element.User;
import cn.support.neo.mvp.model.qualifier.AccountType;
import cn.support.neo.mvp.model.qualifier.ResultCode;
import eu.unicate.retroauth.AuthAccountManager;

import static cn.support.neo.mvp.model.qualifier.AccountType.USER_AVATAR_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_COLLEGE_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_FANS_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_FOCUS_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_ID_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_MOOD_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_NAME_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_NICK_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_PHONENUMBER_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_STUDENT_ID_KEY;
import static cn.support.neo.mvp.model.qualifier.AccountType.USER_VSTATUS_KEY;


public class AccountUtils {

    public static boolean hasUnauthorized(Throwable throwable) {
        if (!(throwable instanceof ResultException)) {
            return false;
        }

        ResultException r = ((ResultException) throwable);
        return r.getErrCode() == ResultCode.TOKEN_OVERDUE;
    }

    public static String getTokenType(Context context) {
        return context.getString(R.string.auth_token_type);
    }

    public static String getAccountType(Context context) {
        return context.getString(R.string.auth_account_type);
    }

    public static String getAccountProperty(Context context, AccountManager accountManager,
                                            AuthAccountManager authAccountManager, String propertyName) {
        Account account = getActiveAccount(context, authAccountManager);
        String propertyValue = accountManager.getUserData(account, propertyName);
        return propertyValue;
    }

    public static String getActiveAccountName(Context context, AuthAccountManager authAccountManager) {
        return authAccountManager.getActiveAccountName(getAccountType(context), false);
    }

    public static Account getActiveAccount(Context context, AuthAccountManager authAccountManager) {
        return authAccountManager.getAccountByName(
                getActiveAccountName(context, authAccountManager),
                getAccountType(context)
        );
    }

    public static void removeAccount(Context context, AccountManager accountManager, AuthAccountManager authAccountManager) {
        accountManager.removeAccount(getActiveAccount(context, authAccountManager), null, null);
    }

    /**
     * 获得Account信息
     */
    public static User getUser(Context context, AuthAccountManager authAccountManager, AccountManager accountManager) {
        Account account = AccountUtils.getActiveAccount(context, authAccountManager);
        User user = new User();
        user.setId(accountManager.getUserData(account, USER_ID_KEY));
        user.setName(accountManager.getUserData(account, USER_NAME_KEY));
        user.setNick(accountManager.getUserData(account, USER_NICK_KEY));
        user.setIcon(accountManager.getUserData(account, USER_AVATAR_KEY));
        user.setPhoneNum(accountManager.getUserData(account, USER_PHONENUMBER_KEY));
        user.setColleage(accountManager.getUserData(account, USER_COLLEGE_KEY));
        user.setStudentId(accountManager.getUserData(account, USER_STUDENT_ID_KEY));
        user.setMood(accountManager.getUserData(account, USER_MOOD_KEY));
        user.setVstatus(Integer.valueOf(accountManager.getUserData(account, USER_VSTATUS_KEY)));
        //新增属性，如果老用户，不重新登陆，会出错
        if (accountManager.getUserData(account, USER_FOCUS_KEY) == null) {
            EventBusProvider.getInstance().post(new UserInfoChangeEvent(null));
        } else {
            user.setFocus(Integer.valueOf(accountManager.getUserData(account, USER_FOCUS_KEY)));
            user.setFans(Integer.valueOf(accountManager.getUserData(account, USER_FANS_KEY)));
        }
        return user;
    }

    public static boolean setUserData(Context context, AuthAccountManager authAccountManager, AccountManager accountManager,
                                      @AccountType String key, String value) {
        Account account = AccountUtils.getActiveAccount(context, authAccountManager);
        accountManager.setUserData(account, key, value);
        if (account == null) return false;
        return true;
    }

    public static Account[] getAccounts(Context context, AccountManager accountManager) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Toast.makeText(context, "请进入设置-应用管理-打开通讯录权限", Toast.LENGTH_LONG).show();
            return null;
        }
        return accountManager.getAccountsByType(getAccountType(context));
    }

    public static boolean hasLoggedIn(Context context, AccountManager accountManager) {
        Account[] accounts = getAccounts(context, accountManager);
        if (accounts != null && accounts.length > 0) {
            Account account = accounts[0];
            //华为有可能 加密 解密失败
            if (account != null) {
                com.orhanobut.logger.Logger.i(account.name);
            } else {
                com.orhanobut.logger.Logger.i("null");
            }

            return !TextUtils.isEmpty(account.name);
        }
        return false;
    }


    public static void needLogin(Activity context, AuthAccountManager authAccountManager) {
        authAccountManager.addAccount(context, getAccountType(context), getTokenType(context));
    }
}